
//
//  ScrawlView.m
//  涂鸦
//
//  Created by 赵博 on 16/6/9.
//  Copyright © 2016年 赵博. All rights reserved.
//

#import "ScrawlView.h"
/*
   1.搭建界面
   2.根据触摸轨迹画线
   2.1 创建一个自定义view触摸事件
   2.2改变颜色，粗细
   2.3 其他
 */
@interface ScrawlView ()

//@property(nonatomic, strong)UIBezierPath *path;
@property(nonatomic, strong)NSMutableArray *paths;

@end

@implementation ScrawlView

-(NSMutableArray *)paths{
    if (_paths == nil) {
        //开辟10个控件的大小
        //如果添加11个对象， 会自动开辟capacity * 2
        _paths = [NSMutableArray arrayWithCapacity:10];
    }
    return _paths;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
*/
- (void)drawRect:(CGRect)rect {
    // Drawing code
    //系统调用 在第一次绘制之前调用
    //在调用此方法之前，已经帮我们床架好了绘图上下文
    for (int i = 0; i< self.paths.count; i++) {
        [self.paths[i] stroke];
    }
    //渲染
}
- (void)deleLayerPath{
    [self.paths removeAllObjects];
    [self setNeedsDisplay];
}
//触摸开始
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //获取手指相对应的UITouch
    UITouch *touch = [touches anyObject];
    //获取手指的点
    CGPoint point = [touch locationInView:touch.view];
    //初始化UIBezierPath
    UIBezierPath *path = [UIBezierPath bezierPath];
    path.lineWidth = 5.0;
    //设置初始点
    [path moveToPoint:point];
    
    //把路径保存到数组中
    [self.paths addObject:path];
    
    
}
//手指移动的时候， 记录触摸的点 并且绘制
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //获取手指相对应的UITouch
    UITouch *touch = [touches anyObject];
    //获取手指的点
    CGPoint point = [touch locationInView:touch.view];
    //获取began的path
    UIBezierPath *path = [self.paths lastObject];
    
    //记录手指移动的点
    [path addLineToPoint:point];
    
    //重绘制
    [self setNeedsDisplay];//重新调用drawRect
    
    
}
//触摸结束的时候， 记录离开的店并绘制
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //调用
    [self touchesMoved:touches withEvent:event];
    
}

@end
